package com.jason.um.user.controller;


import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.jason.common.base.BaseController;
import com.jason.common.error.BusinessErrorEnum;
import com.jason.common.error.BusinessException;
import com.jason.common.vo.CommonReturnType;
import com.jason.um.user.model.UserModel;
import com.jason.um.user.servlce.OtpService;
import com.jason.um.user.servlce.UserService;
import com.jason.um.utils.JWTUtil;
import com.jason.um.utils.SpringSessionManager;
import com.jason.um.utils.StringIdGenerator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.SimpleIdGenerator;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *  用户管理控制器
 * </p>
 *
 * @author jason
 * @version 1.0
 * @date 2019年1月3日
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private OtpService otpService;

//    @Autowired
//    private SpringSessionManager sessionManager;

    private Map<String, String> cacheMap = new ConcurrentHashMap<>();

    /**
     * @return com.jason.common.vo.CommonReturnType
     * @author Jason
     * @description 根据ID获取用户信息
     * @date 2019/1/3 10:29
     * @Param [id]
     **/
    @GetMapping("/{id}")
    public CommonReturnType getUserById(@PathVariable(name = "id") Integer id) throws BusinessException {
        UserModel user = userService.getUserById(id);
        if (user == null) {
            throw new BusinessException(BusinessErrorEnum.USER_NOT_EXIST);
        }
        return CommonReturnType.success(user);
    }

    /**
     * @return com.jason.common.vo.CommonReturnType
     * @Author Jason
     * @Description 获取动态口令
     * 目前是随机生成6位数字，后期可以集成阿里大于短信平台
     * 或者根据电子邮箱发送邮件验证码
     * @Date 2019/1/3 10:25
     * @Param [telephone, session]
     **/
    @GetMapping("/otp")
    public CommonReturnType getOTP(String telephone) throws BusinessException {

        if (StringUtils.isEmpty(telephone)) {
            throw new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR);
        }
        String otp = otpService.getOTP();
        cacheMap.put(telephone, otp);
        // session.setAttribute(telephone, otp);
        log.info("{}的动态验证码为：{}", telephone, otp);
        return CommonReturnType.success("验证码发送成功");

    }

    /**
     * @return com.jason.common.vo.CommonReturnType
     * @Author Jason
     * @Description 口令验证
     * @Date 2019/1/3 10:22
     * @Param [telephone, otpCode, session]
     **/
    @PostMapping("/otp")
    public CommonReturnType getOTP(String telephone, String otpCode) throws BusinessException {

        if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(otpCode)) {
            throw new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR);
        }
        String sessionOtp = cacheMap.get(telephone);
        //String sessionOtp = (String) session.getAttribute(telephone);
        if (!otpCode.equals(sessionOtp)) {
            throw new BusinessException(BusinessErrorEnum.CODE_NOT_VALID);
        }
        return CommonReturnType.success("验证成功");
    }

    /**
     * 注册
     */
    @PostMapping("/registry")
    public CommonReturnType registerByTelephone(@Valid UserModel userModel) throws BusinessException {

        /**
         * 初始化一些注册时未填写的属性
         */
        userModel.setRegType("byPhone");
        userModel.setRegAccount(userModel.getTelephone());

        int i = userService.insertUser(userModel);
        if (i == 1) {
            //注册成功将user信息放入Session
            UserModel user = userService.getUserByTelephone(userModel.getTelephone());
            // sessionManager.saveLoginInfo(user);
            return CommonReturnType.success("注册成功");
        }
        return CommonReturnType.fail("注册失败");
    }

    /**
     *
     * @Author Jason
     * @Description 用户登录
     * @Date 2019/1/3 10:26
     * @Param [telephone, password]
     * @return com.jason.common.vo.CommonReturnType 登陆成功返回一个Token 用于验证请求是否合法m
     **/
    @PostMapping("/launcher")
    public CommonReturnType login(HttpServletRequest request, String telephone, String password) throws BusinessException {
        log.info("telephone: {}, password: {}" , telephone, password);
        if (StringUtils.isEmpty(telephone)) {
            throw new BusinessException(BusinessErrorEnum.USER_AUTH_FAILED);
        }
        Boolean success = userService.authenticate(telephone, password);
        if (!success) {
            throw new BusinessException(BusinessErrorEnum.USER_AUTH_FAILED);
        }
        String origin = request.getHeader("Origin");
        UserModel userModel = userService.getUserByTelephone(telephone);
        //使用Token之后没有必要再使用Session存储用户信息
        //sessionManager.saveLoginInfo(userModel);
        // TODO 生成Token
        String jwtToken = JWTUtil.createJWT(StringIdGenerator.get(), userModel.getName(), "springboot-seckill-server", origin,JWTUtil.DAY_TTL);
        return CommonReturnType.success(jwtToken);
    }

    /**
     * <p> 获取当前登陆用户的详细信息 </p>
     *
     * @return com.jason.common.vo.CommonReturnType
     * @Param [token]
     * @date
     * @author Jason
     **/
    @GetMapping("/info")
    public CommonReturnType info(HttpServletRequest request) throws BusinessException {

        Claims claims = (Claims)request.getAttribute("claims");
        UserModel user = new UserModel();
        //查询用户详细信息
        if (!ObjectUtils.isEmpty(claims)){
            user = userService.getUserById(Integer.valueOf(claims.getId()));
        }
        if (StringUtils.isEmpty(user.getAvatar())){
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }
        return CommonReturnType.success(user);
    }

    /**
     *
     * <p> 安全登出 </p>
     * @Param []
     * @return com.jason.common.vo.CommonReturnType
     * @date
     * @author Jason
     **/
    @PostMapping("/logout")
    public CommonReturnType logout() throws BusinessException {
        return CommonReturnType.success("注销成功");
    }
}
